package com.read.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    public static String signToken(Map map){
        //生成jwt
        //1.定义头部
        Map headMap = new HashMap<>();
        //签名算法
        headMap.put("alg","HS256");
        //类型
        headMap.put("typ","jwt");
        //声明签名算法  密钥 注意 密钥只能 后端知道
        Algorithm algorithm = Algorithm.HMAC256("secret");
        //2. 定义载荷
        String sign = JWT.create().withHeader(headMap)
                //受众  用户
                .withAudience("users")
                //签发人
                .withIssuer("qf-shop")
                //主题
                .withSubject("auth")
                //自定义的公共内容
                .withClaim("name", map.get("username").toString())
                .withClaim("id", map.get("id").toString())
                //签名
                .sign(algorithm);

      return sign;
    }

    public static Boolean verfiyToken(String token){

        //使用jwt进行解密操作
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret"); //use more secure key
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("qf-shop")
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 通过token获取到当前登录用户的id
     * @param token
     * @return
     */
    public static String verfiyTokenGetUserId(String token){

        //使用jwt进行解密操作
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret"); //use more secure key
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("qf-shop")
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("id").asString();
        }catch (Exception e){
            return null;
        }
    }
}
